package com.sbcb.http;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/httpobject")
public class HttpController {

    //通过静态方法获取Request和Response，
    //http://localhost:8080/httpobject/method1
    @GetMapping("method1")
    public String getHTTPObject1() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        Cookie cookie = new Cookie("key", "method1");
        cookie.setMaxAge(1234);
        response.addCookie(cookie);

        return "getHTTPObject1";
    }

    //http://localhost:8080/httpobject/method2
    //通过参数直接获取，只要在你的方法上加上参数，Springboot就会帮你绑定，你可以直接使用。如果你的方法有其他参数，把这两个加到后面即可。
    @GetMapping("method2")
    public String getHTTPObject2(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("key", "method2");
        cookie.setMaxAge(5678);
        response.addCookie(cookie);

        response.addHeader("new-header-name", "new-header-value");
        return "getHTTPObject2";
    }

    //http://localhost:8080/httpobject/setHeader1
    //Using HttpServletResponse
    @GetMapping("setHeader1")
    public String setupHeader1(HttpServletResponse response) {
        response.addHeader("SBP-Example-Header1", "Value-HttpServletResponse1");
        return "Response with header using HttpServletResponse";
    }

    //Using ResponseEntity
    @GetMapping("setHeader2")
    public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("SBP-Example-Header2",
                "Value-ResponseEntityBuilderWithHttpHeaders2");

        System.out.println("usingResponseEntityBuilderAndHttpHeaders");
        return ResponseEntity.ok()
                .headers(responseHeaders)
                .body("Response with header using ResponseEntity");
    }
}
